package com.google.ant.extensions.tasks;

import java.io.File;

import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Mkdir;
import org.apache.tools.ant.taskdefs.Touch;

public abstract class AbstractFantTask extends Task {
    protected static final String LOCAL_REPOSITORY_PROP_NAME = "local.repository.dir";
    protected boolean verbose;
    protected File destdir;

    File localRepository;

    Mkdir mkdirTask;
    Copy copyTask;

    public void setVerbose(boolean v) {
        this.verbose = v;
    }

    public void setDestdir(File to) {
        this.destdir = to;
    }

    public void init() {
        super.init();

        mkdirTask = new Mkdir();
        mkdirTask.setProject(getProject());
        mkdirTask.setTaskName("fant.mkdir");

        copyTask = new Copy();
        copyTask.setProject(getProject());
        copyTask.setTaskName("fant.copy");
        copyTask.setVerbose(this.verbose);

        if (localRepository == null) {
            localRepository = getLocalBase();
            mkdirTask.setDir(localRepository);
            mkdirTask.execute();
        }
    }

    protected File getLocalBase() {
        String localBase = getProject().getProperty(LOCAL_REPOSITORY_PROP_NAME);
        if (localBase == null) {
            localBase = getProject().getProperty("env." + LOCAL_REPOSITORY_PROP_NAME);
        }

        if (localBase == null || localBase.length() == 0) {
            localBase = System.getProperty("user.home") + "/.m2/repository";
        }
        return new File(localBase);
    }

    protected void copy(File file, File todir, boolean overwrite) {
        copyTask.setFile(file);
        copyTask.setTodir(todir);
        copyTask.setOverwrite(overwrite);
        copyTask.execute();
    }

    protected void copy(File file, File todir) {
        copy(file, todir, false);
    }

    protected void touch(File file) {
        Touch touch = new Touch();
        touch.setProject(getProject());
        touch.setTaskName("fant.touch");
        touch.setFile(file);
        touch.execute();
    }
}
